<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .item {
            float: left;
            margin-right: 10px;
            width: 100px;
            height: 50px;
            border: 2px solid black;
        }
    </style>
</head>

<body>
    <script>
        /* let */

        //1-块级作用域
        //使用var
        function f1() {
            var tmp1 = 123;
            if (true) {
                var tmp1 = 234;
            }
            console.log(tmp1);
        }
        f1(); //undefined
        //使用let
        function f2() {
            let tmp2 = 123;
            if (true) {
                let tmp2 = 234;
            }
            console.log(tmp2);
            function f3() {
                console.log("f3");
            }
        }
        f2();
        // f3(); //块级作用域中可以声明函数，但视为let声明，作用域外不可引用


        //2-不能重复声明
        var a = 4;
        var a = 3;
        console.log(a); // 3
        {
            let a = 5;
            // let a = 6; // has already been declared
            console.log(a); // 5
        }

        //3-没有变量提升
        b = 7;
        var b;
        console.log(b); //7
        {
            // b = 6; // cannot access 'b' before initialization
            let b;
        }

        //4-不影响作用域链
        {
            let a = 2;
            function fn() {
                console.log(a);
            }
            fn(); // 2
        }

        //5-暂时性死区(无变量提升、变量形成封闭作用域导致)
        {
            var x = x; // 不报错
            // let x = x; // is not defined 右边的x未声明
        }
        var x = 4;
        {
            x = 6;
            // let x; // 未初始化,此时x已经不再是全局变量
        }
    </script>
    <div>
        <h1>let应用 - 点击切换颜色</h1>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <script>
        let items = document.getElementsByClassName("item");
        for (let i = 0, length = items.length; i < length; i++) {
            items[i].onclick = function () {
                this.style.backgroundColor = "black";
            };
        }
    </script>
    <script>
        /* const */
        const sex = "women";
        //1-常量不允许修改 2-一般使用大写 3-有块级作用域 4-一定要赋初始值 5-不允许重复声明
        const ARRAY = [1, 2, 3];
        ARRAY.push(4);
        console.log(ARRAY);
        const OBJ = {};
        OBJ.name = "test";
        console.log(OBJ);
        // const声明指向引用，即地址，对于对象不可以修改他的地址，但可以修改内部的属性
    </script>
</body>

</html>